<template>
  <el-form size="mini" :model="userFormData" status-icon :rules="rules" ref="userFormRef" label-width="90px">
    <el-form-item label="姓名" prop="realname">
      <el-input type="text" v-model="userFormData.realname" autocomplete="off"></el-input>
      <span class="el-icon-warning-outline tip" v-if="!errorFields.includes('realname')">
        姓名为身份证中的名称</span>
    </el-form-item>
    <el-form-item label="账号" prop="username">
      <el-input type="text" v-model="userFormData.username" autocomplete="off"></el-input>
      <span class="el-icon-warning-outline tip" v-if="!errorFields.includes('username')">
        账号要为全英文字母或数字组成</span>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="text" v-model="userFormData.password" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="角色" prop="role">
      <el-select v-model="userFormData.role" filterable placeholder="请选择角色">
        <el-option v-for="item in roles" 
        :key="item.id" 
        :label="item.cname"
         :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="userFormData.sex">
        <el-radio label="1">先生</el-radio>
        <el-radio label="2">女士</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input type="text" v-model="userFormData.phone" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="生日" prop="birthday">
      <el-date-picker type="date"
       placeholder="选择日期"
        value-format="yyyy-MM-dd"
        v-model="userFormData.birthday">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="头像" >
            <!-- 
        action必填string,图片上传的url地址,
        accept 接受的图片格式
      -->
      <el-upload
  class="avatar-uploader"
  :action="uploadActionUrl"
  :show-file-list="false"
  accept=".jpg,.jpeg,.gif,.png"

  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imgUrl" :src="imgUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  <div class="el-upload__tip" slot="tip">只能上传jpg/png/gif文件，且不超过1MB</div>

</el-upload>

    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('userFormRef')">提交</el-button>
      <el-button @click="resetForm('userFormRef')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getFullYearDay } from '@/utils/tools'
import { addUserApi, uploadAvatarApi } from '@/api/userApi'
import { rolesApi } from '@/api/roleApi'

import { addUserRulesMixin } from '../mixin'
export default {
  mixins: [addUserRulesMixin],
  props: ['setDialogVisible'],//接受父组件传来的方法，实现在点击提交后关闭弹出框
  data() {
    return {
      imgUrl:'',
      roles:[],
      userFormData: {
        realname: '',
        username: '',
        password: '',
        sex: '1',
        phone: '13521512512',
        birthday: getFullYearDay()[0],
        avatar:'',
        role:''
      },
    }
  },
  computed: {
    // 返回头像图片上传的路径地址
    uploadActionUrl() {
      // return process.env.VUE_APP_APIHOST + '/api/user/uploadAvatar'
      return ''
    }
  },
  //调用获取角色列表方法
  created() {
    this.loadRoles()
  },
  methods: {
    //获取角色列表
    async loadRoles() {
      let ret = await rolesApi(1, 999)     //第一页请求999个数据
      this.roles = ret.data.roles
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid, errors) => {
        this.errorFields = Object.keys(errors)//errors为对象，包括未输入的属性，存入errorFields数组中用来判断显示提示文字
        if (valid) {
          let ret = await addUserApi(this.userFormData)
          if(ret.code===0){
            // 新增用户成功
            this.$message({
              message: '新增用户成功！',
              type: 'success',
              showClose: true,//手动关闭
              duration: 3000,
              onClose: () => {
                // 关才弹出层之前，需要对表单项进行清空操作
                this.resetForm(formName)
                // 添加成功后，后端接口返回数据后，关闭当前弹出层
                this.setDialogVisible(false)
              }
            })

          }else{
            // 提示一下
            this.$message({
              message: '新增用户失败，请认真检查填写的内容！',
              type: 'error',
              duration: 3000
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 在上传之前完成对于文件类型的限制和大小的限制
    // true继续上传,false中止
    async beforeAvatarUpload(file){
      // console.log(file);
      const isSize = file.size <= 1024 * 1024
      if(!isSize) {
        this.$alert('当前上传的头像过大,超过1MB', { showClose: true })
      return true
    }
    //限制当前上传的文件它只能是图片 作为验证方法用于验证
    let allowImage = ['image/jpeg', 'image/gif', 'image/png','image/jpg']
    const isType = allowImage.includes(file.type)       //验证方法的数组中包含上传图片的格式
    if (!isType) {    //判断这个布尔值变量，当上传文件不符合条件时
        this.$alert('当前上传的头像是一个不合法的文件,只能上传图片', {
          showClose: true
        })
        return false
      }
 // 限制上传的文件的长宽比例
 const img = new Image()
 img.src=window.URL.createObjectURL(file)
//  将图片的原始宽高赋值给变量
 const h = img.naturalHeight
 const w = img.naturalWidth
 //判断图片的数据是否符合条件
 if ((h >= 100) & (h <= 300) || (w >= 60 && w <= 600)) {
        this.$alert('当前上传的图片长或宽不符合上传的尺寸要求', {
          showClose: true
        })
        return false
      }
      // 调用定义的上传方法完成上传 FormData
      const formData=new FormData()
      
      formData.append('file',file)
      let ret =await uploadAvatarApi(formData)
      console.log(formData.file);
      if(ret.code===0){
        console.log(ret.data.url);
        this.imgUrl=ret.data.url,
        this.userFormData.avatar=ret.data.filepath
        // console.log(this.imgUrl);
      }
      return false   //取消自动上传
},
//该方法可以不使用，以为没有自动上传不会调用该方法
  handleAvatarSuccess(response){
    //response为后端data传来的数据，包括filepath和url
      // console.log(response)
      if(response.code===0){          //上传成功
        this.imgUrl=response.data.url,
        this.userFormData.avatar=response.data.filepath
      }
    }
} 
  }      
</script>


<style lang="stylus" scoped>
$wh = 100px

.tip
  color: #c0c4cc
  font-size: 12px

.avatar-uploader
  & :deep(.el-upload)
    border: 1px dashed #d9d9d9
    border-radius: 6px
    cursor: pointer
    position: relative
    overflow: hidden

  & :deep(.el-upload:hover)
    border-color: #409eff

.avatar-uploader-icon
  font-size: 28px
  color: #8c939d
  width: $wh
  height: $wh
  line-height: $wh
  text-align: center

.avatar
  width: $wh
  height: $wh
  display: block
</style>
